package io.renren.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.Result;
import io.renren.modules.sp.excel.SpSignRecordExcel;
import io.renren.modules.sp.service.SpMatchItemImportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public class SpImportMatchScoreListener extends AnalysisEventListener<SpSignRecordExcel> {

    private Result result;
    private RedisUtils redisUtils;

    private SpMatchItemImportService spMatchItemImportService;
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 200;
    private static int PROCESS, TOTAL = 0;
    List<SpSignRecordExcel> list = new ArrayList<SpSignRecordExcel>();

    private int matchItemId;

    public SpImportMatchScoreListener(SpMatchItemImportService userService, Result result, RedisUtils redisUtils, int matchItemId) {
        this.spMatchItemImportService = userService;
        this.result = result;
        this.redisUtils = redisUtils;
        this.matchItemId = matchItemId;
    }

    @Override
    public void invoke(SpSignRecordExcel data, AnalysisContext context) {
        // 空行校验：检查关键字段是否全部为空
        if (isBlankRow(data)) {
            log.info("跳过空行数据");
            return;
        }

        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        PROCESS++;
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            updData();
            list.clear();
        }
    }

    private boolean isBlankRow(SpSignRecordExcel data) {
        return StringUtils.isEmpty(data.getId()) &&
                StringUtils.isEmpty(data.getTeamName()) &&
                StringUtils.isEmpty(data.getRealName()) &&
                StringUtils.isEmpty(data.getCompany());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        updData();
        TOTAL = 0;
        PROCESS = 0;
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void updData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            List<SpSignRecordExcel> saveList = new ArrayList();
            // 校验数据是否合法
            for(SpSignRecordExcel excel : list){
                try{
                    spMatchItemImportService.checkMatchScore(excel, matchItemId);
                }catch (Exception e){
                    e.printStackTrace();
                    result.error(e.getMessage());
                }
            }
            boolean flag = true;
            for(SpSignRecordExcel excel : list){
                if(!StringUtils.isEmpty(excel.getCheckMsg())){
                   flag = false;
                   break;
                }
            }
            if(!flag){
                String errorCode = UUID.randomUUID().toString();
                redisUtils.set(errorCode, JSONArray.toJSONString(list),1000);
                result.setCode(500);
                result.setMsg(errorCode);
                return;
            }


            for(SpSignRecordExcel excel : list){
                spMatchItemImportService.importMatchScore(excel);
            }
            try{
                TOTAL += saveList.size();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.info("存储数据库成功！");
    }
}
